<?php


namespace app\index\controller;


use app\common\model\Users;
use app\index\validate\LoginValidate;
use app\index\validate\RegisterValidate;
use think\Controller;

class Index extends Base
{
    public function index(){
        $Recommend = model('project')->order('create_time','desc')->limit(4)->select();
        $banner    = model('banner')->order('sort')->select();
        $download = model('download')->order('create_time','desc')->limit(10)->select();
        $article = model('article')->limit(10)->select();
        $new_article = model('article')->order('create_time','desc')->limit(10)->select();
        $this->assign(compact('Recommend','banner','download','article','new_article'));
        return view();
    }
    public function login(){
        if(request()->isPost()){
            $data = input('post.');
            $result = $this->validate($data,LoginValidate::class);
            if(true !== $result){
                $this->error($result);
            }
            $user = new Users;
            $result = $user->where($data)->find();
            if($result){
                if ($result['status'] != 1) {
                    $this->error($result['status']==0 ? "正在等待管理员审核" : "您未审核通过");
                }
                $result['update_time'] = time();
                $session = [
                    'id'       => $result['id'],
                    'name'     => $result['name'],
                    'create_time' => $result['create_time'],
                    'vol_true_name' => $result['vol_true_name'],
                    'update_time' => $result['update_time']
                ];
                session('vol_user', $session);
                $result->save();
                $this->success('登录成功','index/index/index');
            }else{
                $this->error('账号或密码错误');
            }
        }
        return view();
    }
    public function register(){
        if(request()->isPost()){
            $data = input('post.');
            $result = $this->validate($data,RegisterValidate::class);
            if(true !== $result){
                $this->error($result);
            }
            $user = new Users;
            $user->save($data);
            $this->success('注册信息提交成功！等待管理员审核');
        }
        return view();
    }

    public function loginOut(){
        session(null);
        if (session('?vol_user.id')) {
            $this->error('退出失败！');
        } else {
            $this->success('退出成功', 'index/index/login');
        }
    }
}
